/*   
 * Copyright 2009-2010 Rob Schoening
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 *    
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.beaconframework.vaadin.data;

import java.util.HashMap;
import java.util.Map;

import org.beaconframework.util.exception.BeaconException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class QueryTemplate<T> {

    private static Logger log = LoggerFactory.getLogger(QueryTemplate.class);


    public abstract Object doExecuteQuery(Map<String, Object> arg)
            throws Exception;


    @SuppressWarnings("unchecked")
    public T doTransform(Object input) throws Exception {
        return (T) input;
    }


    public abstract T doHandleException(Exception t) throws Exception;


    public final T query(Object obj) {
        Map<String, Object> m = new HashMap<String, Object>();
        m.put(index(0), obj);
        return query(m);
    }


    public final T query(Map<String, Object> arg) {
        try {
            Object queryResult = doExecuteQuery(arg);
            return doTransform(queryResult);
        }

        catch (Exception e) {
            try {
                T r = doHandleException(e);
                return r;
            }

            catch (RuntimeException e2) {
                throw e2;
            } catch (Exception e2) {
                throw new BeaconException(e2);
            }
        }
    }


    public String index(int i) {
        return "arg" + i;
    }

}
